package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.domain.SetmealDish;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 分页查 mybatisPlus实现
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    /*
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotBlank(name), Dish::getName, name);
        lqw.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo, lqw);

        Page<DishDto> dishDtoPage = new Page<>();
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((record) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(record, dishDto);
            Long categoryId = record.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }*/

    /**
     * 分页查询  原生mybatis实现
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    /*@GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        Page<DishDto> pageInfo = dishService.pageByName(page,pageSize,name);
        return R.success(pageInfo);
    }*/

    /**
     * 分页查询   优化sql
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //构建分页
        Page<Dish> dishPage = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //模糊查询
        lqw.like(StringUtils.isNotBlank(name),Dish::getName,name);
        //排序
        lqw.orderByDesc(Dish::getUpdateTime);
        //查询原始数据
        dishService.page(dishPage,lqw);

        Page<DishDto> dishDtoPage = new Page<>();
        //将原始数据集除了records拷贝至dishDtoPage
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");
        //原始数据集
        List<Dish> records = dishPage.getRecords();
        //获取所有菜品的分类id集合
        Set<Long> set = records.stream().map(Dish::getCategoryId).collect(Collectors.toSet());
        //根据分类id集合获取分类集合
        List<Category> list = categoryService.listByIds(set);
        //List转Map key:分类id value:菜品分类名称
        Map<Long, String> map = list.stream().collect(Collectors.toMap(Category::getId, Category::getName));
        List<DishDto> dishDtoList = records.stream().map(record -> {
            DishDto dishDto = new DishDto();
            //dish中的数据拷贝到dishDto
            BeanUtils.copyProperties(record, dishDto);
            //设置分类名称
            dishDto.setCategoryName(map.get(record.getCategoryId()));
            return dishDto;
        }).collect(Collectors.toList());
        //设置dishDtoPage的数据集
        dishDtoPage.setRecords(dishDtoList);
        return R.success(dishDtoPage);
    }
    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    @CacheEvict(cacheNames = "setmeal",allEntries = true)
    public R<String> saveWithFlavor(@RequestBody DishDto dishDto) {
        log.info("新增菜品:{}", dishDto);
        dishService.saveWithFlavor(dishDto);

        //删除当前分类id下缓存中的数据
        Set keys = redisTemplate.keys("dish_"+dishDto.getCategoryId()+"_1"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys); //删除这些key
        return R.success("添加成功");
    }

    /**
     * 根据id批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> deleteByIds(@RequestParam List<Long> ids) {
        log.info("删除菜品的id:{}", ids);
        dishService.deleteByIds(ids);
        /*for (Long id : ids) {
            dishService.removeById(id);
        }*/

        //删除缓存中所有的菜品信息
        Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys); //删除这些key
        return R.success("删除成功");
    }

    /**
     * 批量停售/启售
     *
     * @param status
     * @param ids
     * @return
     */
    @CacheEvict(cacheNames = "setmeal",allEntries = true)
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable int status, Long[] ids) {
        log.info("修改菜品的id:{}", Arrays.toString(ids));
        List<Long> list = Arrays.stream(ids).collect(Collectors.toList());
        List<Dish> dishes = dishService.listByIds(list);
        dishes.forEach(dish -> dish.setStatus(status));
        dishService.updateBatchById(dishes);
        /*for (Long id : ids) {
            Dish dish = dishService.getById(id);
            dish.setStatus(status);
            dishService.updateById(dish);
        }*/

        //删除缓存中所有的菜品信息
        Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys); //删除这些key
        return R.success("修改成功");
    }

    /**
     * 根据id查询菜品信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id) {
        DishDto dishDto = null;
        String key = "dish_"+id;
        dishDto = (DishDto) redisTemplate.opsForValue().get(key);
        if (dishDto != null){
            //如果缓存中有数据,直接返回
            return R.success(dishDto);
        }
        log.info("查询菜品的id:{}", id);
        dishDto = dishService.getByIdWithFlavor(id);
        //存入缓存
        redisTemplate.opsForValue().set(key,dishDto,1,TimeUnit.HOURS);
        return R.success(dishDto);
    }

    /**
     * 修改菜品信息
     *
     * @param dishDto
     * @return
     */
    @CacheEvict(cacheNames = "setmeal",allEntries = true)
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info("修改菜品信息:{}",dishDto);
        dishService.updateWithFlavor(dishDto);

        //删除缓存中所有的菜品信息
        Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys); //删除这些key
        return R.success("修改成功");
    }

    /**
     * 根据条件查询对应的菜品数据
     *
     * @param dish
     * @return
     */
    /*@GetMapping("/list")
    public R<List<Dish>> list(Dish dish){
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //查询起售
        lqw.eq(Dish::getStatus,1);
        //根据菜品分类id查询
        lqw.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //根据菜品名称模糊查询
        lqw.like(StringUtils.isNotBlank(dish.getName()),Dish::getName,dish.getName());
        //根据修改时间倒序排序
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(lqw);
        return R.success(list);
    }*/


    @GetMapping("/list")
    public R<List<DishDto>> listWithDishFlavor(Dish dish){
        List<DishDto> dishDtoList = null;
        //动态构造key
        String key = "dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        //从Redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoList!=null){
            //如果存在,直接返回,不查询数据库
            return R.success(dishDtoList);
        }
        //如果不存在,查询数据库
        dishDtoList = dishService.listWithFlavor(dish);
        //将查询到的数据存入Redis中,设置过期时间
        redisTemplate.opsForValue().set(key,dishDtoList,1, TimeUnit.HOURS);
        return R.success(dishDtoList);
    }


}
